// #include <iostream>
// #include "hv/hv.h"
// #include "hv/TcpClient.h"

// int main(int argc, char *argv[])
// {
//   hv::EventLoop loop;
//   hv::TcpClient client(new hv::TcpClient(&loop));
//   client->onMessage(
//       [](const hv::TcpConnPtr &conn, hv::Buffer *buf)
//       {
//         std::string data = buf->toString();
//         if (data[0] == '1')
//         {
//           conn->send("2 bye server!\n");
//           std::cout << "2 bye server!" << std::endl;
//         }
//         if (data[0] == '3')
//         {
//           std::cout << "c: I will close" << std:endl;
//           int closeStatus = loop.close();
//           std::cout << "c: close status:" << closeStatus << std::endl;
//         }
//       });
//   client->connect("127.0.0.1", 8888);
//   // 发送数据
//   client->send("0 hello server!");
//   std::cout << "0 hello server" << std::endl;
//   loop.loop();
//   return 0;
// }
#include <iostream>
#include "hv/TcpClient.h"
using namespace hv;

int main() {
    int port = 1234;
    TcpClient cli;
    int connfd = cli.createsocket(port);
    if (connfd < 0) {
        return -1;
    }
    cli.onConnection = [](const SocketChannelPtr& channel) {
        std::string peeraddr = channel->peeraddr();
        if (channel->isConnected()) {
            printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
        } else {
            printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
        }
    };
    cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
        printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
    };
    cli.start();

    std::string str;
    while (std::getline(std::cin, str)) {
        if (str == "close") {
            cli.closesocket();
        } else if (str == "start") {
            cli.start();
        } else if (str == "stop") {
            cli.stop();
            break;
        } else {
            if (!cli.isConnected()) break;
            cli.send(str);
        }
    }
    return 0;
}